const wssrouter = require('koa-router')()
const { msg } = require("../models/msg")
const { user } = require("../models/user")
var uws = []
var level = 0  //0 1 2 3 4
wssrouter.get('/scj', async (ctx, next) => {
    if (!ctx.request.query.level) {
        level = 0
    }
    level = ctx.request.query.level
    ctx.body = {
        level: level
    }

})

wssrouter.get('/cj', async (ctx, next) => {
    ctx.body = {
        level: level
    }
    level = 0
})


wssrouter.get('/ocj', async (ctx, next) => {
    ctx.body = {
        level: level
    }
})



const refreshListInfo = async (uws) => {
    let list = await user.find()

    uws.forEach(e => {
        let obj = {
            type: 'list',
            data: list
        }
        e.send(JSON.stringify(obj))
    })

}
const dealLastWord = (id, obj) => {
    return new Promise(async (resolve, reject) => {
        let res = await user.findOne({
            uid: id
        })

        if (res) {
            let index = res.lastMsg.findIndex(e => e.fid == obj.fid && e.tid == obj.tid)
            if (index === -1) {
                res.lastMsg.push(obj)
            } else {

                res.lastMsg[index].fid = obj.fid
                res.lastMsg[index].tid = obj.tid
                res.lastMsg[index].lastword = obj.lastword
            }
            res.save().then(() => {
                console.log('保存最后一次聊天信息成功')
                resolve(0)
            }).catch((err) => {
                console.log('保存最后一次聊天信息成功失败', err)
                reject(1)
            })


        } else {

        }


    })




}

const refreshOrCreateUserInfo = async (uws, id) => {
    user.findOne({
        uid: id
    }).then(res => {
        if (res) {
            console.log('更新并推送列表')
            user.findOneAndUpdate(
                { uid: id }, { $set: { isOnline: true } }, { returnDocument: "after" }).then(res => {
                    refreshListInfo(uws, id)
                })
        } else {
            console.log('创建用户')
            user.create({
                uid: id,
                loginTime: new Date().getTime(),
                isOnline: true
            }).then(res => {
                refreshListInfo(uws, id)
            })
        }
    })
}
wssrouter.get('/getChatHistory', async (ctx, next) => {
    let res = ctx.request.query
    const { fid, tid } = res
    let msglist = await msg.find({
        fid: {
            $in: [fid, tid]
        },
        tid: {
            $in: [fid, tid]
        },
    })

    ctx.body = msglist.length == 0 ? [] : msglist
})




wssrouter.post('/modifyUserInfo', async (ctx, next) => {
    let res = ctx.request.body
    let ures = await user.findOne({
        _id: res.fdata._id
    })
    if (ures) {
        const messageToUpdate = ures.lastMsg.find(user =>
            user.fid == res.sdata.fid && user.tid == res.sdata.tid
        )
        messageToUpdate.unreadnum += 1

        let ffres = await ures.save()
        if (ffres) {
            let msglist = await user.find()

            ctx.body = {
                code: 200,
                data: msglist
            }
        }

    } else {

    }



})

wssrouter.post('/readUnreadInfo', async (ctx, next) => {
    let res = ctx.request.body
    let ures = await user.findOne({
        _id: res.fdata._id
    })

    if (ures) {
        const messageToUpdate = ures.lastMsg.find(user =>
            user.fid == res.sdata.fid && user.tid == res.sdata.tid
        )
        console.log(messageToUpdate, 'messageToUpdate')
        messageToUpdate.unreadnum = 0
        let ffres = await ures.save()
        if (ffres) {
            let msglist = await user.find()

            ctx.body = {
                code: 200,
                data: msglist
            }
        }

    } else {
        console.log(222222222)
    }



})







module.exports = {
    WebSocketApi: (wss) => {

        // 当有客户端连接时
        wss.on('connection', function connection(ws) {
            // 当收到消息时
            ws.on('message', async function incoming(message) {
                let obj = JSON.parse(message);
                if (obj.opType === 'msg') {
                    msg.create({
                        fid: obj.fid,
                        tid: obj.tid,
                        time: obj.time,
                        content: obj.content,
                        isRead: false
                    })


                    dealLastWord(obj.fid, {
                        fid: obj.fid,
                        tid: obj.tid,
                        lastword: obj.content
                    }).then(res => {
                        dealLastWord(obj.tid, {
                            fid: obj.fid,
                            tid: obj.tid,
                            lastword: obj.content
                        }).then(res1 => {
                            refreshListInfo(uws)
                        }).then(async (res) => {
                            let msglist = await msg.find({
                                fid: {
                                    $in: [obj.fid, obj.tid]
                                },
                                tid: {
                                    $in: [obj.fid, obj.tid]
                                },
                            })

                            uws.forEach((e, i) => {
                                if (
                                    [obj.fid, obj.tid].includes(e.uid)
                                ) {

                                    let obj = {
                                        type: 'message',
                                        data: msglist
                                    }

                                    e.send(JSON.stringify(obj))
                                }


                            })
                        })
                    })





                } else {
                    if (!uws.map(e => e.uid).includes(obj.uid)) {
                        //如果没有此用户
                        ws.uid = obj.uid
                        uws.push(ws)
                        refreshOrCreateUserInfo(uws, obj.uid)
                    } else {
                        let index = uws.findIndex(e => e.uid === obj.uid)
                        ws.uid = obj.uid
                        uws[index] = ws
                        refreshOrCreateUserInfo(uws, obj.uid)
                    }
                }


            });

            // 当连接关闭时
            ws.on('close', function () {

                user.findOne({
                    uid: ws.uid
                }).then(res => {
                    if (res) {

                        user.findOneAndUpdate({
                            uid: res.uid,
                        }, { $set: { isOnline: false } },            // 更新操作
                            { returnDocument: "after" }).then(async res => {
                                console.error(res.uid, '客户端断开连接');
                                let list = await user.find()
                                uws.forEach((e, i) => {
                                    let obj = {
                                        type: 'list',
                                        data: list
                                    }

                                    e.send(JSON.stringify(obj))
                                    if (i == uws.length - 1) {
                                        console.error(`${ws.uid}群发断开连接信息`);
                                    }


                                })
                            })
                    } else {
                        console.error('非法客户端断开');
                    }
                })

            });
        });
    },
    wssrouter: wssrouter
}

